$(function () {
  /******************************************初始化部分******************************************/
  const table = layui.table;
  // 选中的应用产品的id list
  let applyProductIdList=[]
  // 选中的算法产品的id list
  let algProductIdList=[]
  // tab index
  let index=0
  // 服务产品查询参数
  let serviceProductParams = {
    sourceType: 3, //产品类型 5应用产品 3算法产品
    ownUserId: sessionStorage.getItem("UserId"),
    currPage: 0,
    pageSize: 10,
  };
  //应用产品表格实例
  const applyProductTable = table.render({
    elem: "#applyProductTable",
    height: ".layui-tab-item",
    data:[],
    cols: [
      [
        //表头
        {type:'checkbox', width:60},
        { type: "numbers", title: "序号", width: 60 },
        { field: "productName", title: "产品名称" },
        { field: "productMixName", title: "混合套餐名称" },
        { field: "buyCount", title: "申购次数" },
        {
          field: "status",
          title: "状态",
          templet: function (d) {
            switch (d.status) {
              case -2:
                return `<span>被退回</span>`;
              case -1:
                return `<span>待提交</span>`;
              case 0:
                return `<span>已上架</span>`;
              case 1:
                return `<span>已下架</span>`;
              case 2:
                return `<span>待审核</span>`;
              case 3:
                return `<span>未测试</span>`;
              default:
                return ``;
            }
          },
        },
        { field: "buyCount", title: "评分" },
        { field: "remark", title: "备注" },
        {
          title: "操作",
          width: 200,
          templet: function (d) {
            switch (d.status) {
              case -2:
              case -1:
                return `<a class="layui-btn layui-btn-xs layui-btn-normal text-white mr-2" lay-event="edit">修改</a>
									<a class="layui-btn layui-btn-xs layui-btn-warm text-white mr-2" lay-event="delete">删除</a>
									<a class="layui-btn layui-btn-xs layui-btn-warm text-white mr-2" lay-event="submit">提交</a>`;
              case 0:
                return `<a class="layui-btn layui-btn-xs text-white mr-2" lay-event="detail">详情</a>
									<a class="layui-btn layui-btn-xs layui-btn-danger text-white mr-2"  lay-event="takeDown">下架</a></td>`;
              case 1:
              case 2:
                return `<a class="layui-btn layui-btn-xs layui-btn-normal text-white mr-2" lay-event="edit">修改</a>
									<a class="layui-btn layui-btn-xs layui-btn-warm text-white mr-2" lay-event="delete">删除</a>`;
              case 3:
                return `<a class="layui-btn layui-btn-xs text-white mr-2" lay-event="detail">详情</a>
									<a class="layui-btn layui-btn-xs layui-btn-danger text-white mr-2" lay-event="test">测试</a></td>`;
              default:
                return ``;
            }
          },
        },
      ],
    ],
  });
  // 混合套餐产品查询参数
  let mixPackageProductParams = {
    currPage: 0,
    pageSize: 10,
  };
  //算法产品表格实例
  const algProductTable = table.render({
    elem: "#algProductTable",
    data: [],
    cols: [
      [
        //表头
        {type:'checkbox', width:60},
        { type: "numbers", title: "序号", width: 60 },
        { field: "productName", title: "产品名称" },
        { field: "algName", title: "算法名称" },
        {
          field: "status",
          title: "状态",
          templet: function (d) {
            switch (d.status) {
              case -2:
                return `<span>被退回</span>`;
              case -1:
                return `<span>待提交</span>`;
              case 0:
                return `<span>已上架</span>`;
              case 1:
                return `<span>已下架</span>`;
              case 2:
                return `<span>待审核</span>`;
              case 3:
                return `<span>未测试</span>`;
              default:
                return ``;
            }
          },
        },
        { field: "buyCount", title: "申购次数（次）" },
        { field: "score", title: "评分" },
        {
          title: "操作",
          width: 200,
          templet: function (d) {
            switch (d.status) {
              case -2:
              case -1:
                return `<a class="layui-btn layui-btn-xs layui-btn-normal text-white mr-2" lay-event="edit">修改</a>
									<a class="layui-btn layui-btn-xs layui-btn-warm text-white mr-2" lay-event="delete">删除</a>
									<a class="layui-btn layui-btn-xs layui-btn-warm text-white mr-2" lay-event="submit">提交</a>`;
              case 0:
                return `<a class="layui-btn layui-btn-xs text-white mr-2" lay-event="detail">详情</a>
									<a class="layui-btn layui-btn-xs layui-btn-danger text-white mr-2" lay-event="takeDown">下架</a></td>`;
              case 1:
              case 2:
                return `<a class="layui-btn layui-btn-xs layui-btn-normal text-white mr-2" lay-event="edit">修改</a>
									<a class="layui-btn layui-btn-xs layui-btn-warm text-white mr-2" lay-event="delete">删除</a>`;
              case 3:
                return `<a class="layui-btn layui-btn-xs text-white mr-2" lay-event="detail">详情</a>
									<a class="layui-btn layui-btn-xs layui-btn-danger text-white mr-2" lay-event="test">测试</a></td>`;

              default:
                return ``;
            }
          },
        },
      ],
    ],
  });
  /******************************************事件处理部分******************************************/
  // 服务产品注册
  $("#serviceProductRegistrat").click(function () {
    window.dataProductId = null;
    layer.open({
      type: 2,
      title: "服务产品注册",
      area: ["800px", "600px"],
      content: "./popupPage/serviceProductRegistratPop.html",
    });
  });
  //监听tab切换组装数据
  layui.element.on("tab(serviceProductManager)", function (data) {
    index = data.index;
    requestStatistic(index);
    if (index == 1) {
      $(".showTips")
          .eq(1)
          .removeClass("disabledNone")
          .siblings(".showTips")
          .addClass("disabledNone");
      serviceProductTableRender(5);
    } else if (index === 0) {
      $(".showTips")
          .eq(0)
          .removeClass("disabledNone")
          .siblings(".showTips")
          .addClass("disabledNone");
      serviceProductTableRender(3);
    } else if (index === 2) {
      mixPackageProductTableAndPageRender();
      $(".showTips")
          .eq(0)
          .removeClass("disabledNone")
          .siblings(".showTips")
          .addClass("disabledNone");
    }
  });
  // 应用产品表格复选框选中事件
  table.on('checkbox(applyProductTable)', function(obj){
    if (obj.type==='all'&&obj.checked){
      applyProductIdList=table.cache['applyProductTable'].map(item=>item.id);
      // console.log('ids', ids)
    }else if (obj.type==='one'&&obj.checked){//选中
      applyProductIdList.push(obj.data.id)
      console.log('sourceIdList', applyProductIdList)
    }else if (obj.type==='all'&&!obj.checked){//取消选中
      applyProductIdList=[]
    }else if (obj.type==='one'&&!obj.checked){//取消选中
      // 查找值的索引
      const index = applyProductIdList.indexOf(obj.data.id);
      if (index !== -1) {
        applyProductIdList.splice(index, 1);
      }
    }
  });
  // 算法产品表格复选框选中事件
  table.on('checkbox(algProductTable)', function(obj){
    if (obj.type==='all'&&obj.checked){
      algProductIdList=table.cache['algProductTable'].map(item=>item.id);
      // console.log('ids', ids)
    }else if (obj.type==='one'&&obj.checked){//选中
      algProductIdList.push(obj.data.id)
    }else if (obj.type==='all'&&!obj.checked){//取消选中
      algProductIdList=[]
    }else if (obj.type==='one'&&!obj.checked){//取消选中
      // 查找值的索引
      const index = algProductIdList.indexOf(obj.data.id);
      if (index !== -1) {
        algProductIdList.splice(index, 1);
      }
    }
  });
  // 批量提交审核算法产品或应用产品按钮
  $("#submitDataServiceAll").on('click',function (){
    if ((index===0&&algProductIdList.length>0)||(index===1&&applyProductIdList.length>0)){
      $.ajax({
       timeout:30000,
        url: window.Http + '/dataProduct/commit',
        type:'PUT' ,
        headers: {
          'Authorization': "Bearer " + sessionStorage.getItem('Token')
        },
        data:{
          ids:index===0?algProductIdList.join(','):applyProductIdList.join(','),
          type:7//7服务产品
        },
        success: function (res) {
          if (res.code === 200) {
            layer.msg('提交成功')
            algProductIdList=[]
            applyProductIdList=[]
          } else {
            layer.msg(res.msg)
          }
        }
      })
    }else {
      layer.msg('当前未选中数据')
    }
  })
  // 批量删除算法产品或应用产品按钮
  $('#deleteDataServiceAll').on('click',function (){
    if ((index===0&&algProductIdList.length>0)||(index===1&&applyProductIdList.length>0)){
      const idList=index===0?algProductIdList.join(','):applyProductIdList.join(',')
      $.ajax({
       timeout:30000,
        url: window.Http + '/dataProduct/'+idList,
        type:'DELETE' ,
        headers: {
          'Authorization': "Bearer " + sessionStorage.getItem('Token')
        },
        success: function (res) {
          if (res.code === 200) {
            layer.msg('删除成功')
            algProductIdList=[]
            applyProductIdList=[]
            serviceProductTableRender(index===0?3:5);
          } else {
            layer.msg(res.msg)
          }
        }
      })
    }else {
      layer.msg('当前未选中数据')
    }
  })
  // 算法产品详情、修改等跳转
  table.on("tool(algProductTable)", function (obj) {
    const data = obj.data;
    if (obj.event === "detail") {
      //详情
      window.location.href = "./serverProductDetial.html?productId=" + data.id;
    } else if (obj.event === "edit") {
      //修改
      window.dataProductId = data.id;
      layer.open({
        type: 2,
        title: "服务产品修改",
        area: ["1200px", "800px"],
        content: "./popupPage/serviceProductRegistratPop.html",
      });
    } else if (obj.event === "takeDown") {
      //下架
      $.ajax({
       timeout:30000,
        url: window.Http + "/dataProduct/operate",
        type: "POST",
        headers: {
          Authorization: "Bearer " + sessionStorage.getItem("Token"),
        },
        data: JSON.stringify({ id: dataId, status: -1 }),
        contentType: "application/json",
        success: function (res) {
          if (res.code === 200) {
            layer.msg("下架成功", { icon: 1 });
            algProductListReq();
          } else {
            layer.msg("下架异常", { icon: 2 });
          }
        },
      });
    } else if (obj.event === "shelves") {
      //上架
      $.ajax({
       timeout:30000,
        url: window.Http + "/dataProduct/operate",
        type: "POST",
        headers: {
          Authorization: "Bearer " + sessionStorage.getItem("Token"),
        },
        data: JSON.stringify({ id: dataId, status: 1 }),
        contentType: "application/json",
        success: function (res) {
          if (res.code === 200) {
            layer.msg("上架成功", { icon: 1 });
            algProductListReq();
          } else {
            layer.msg("上架异常", { icon: 2 });
          }
        },
      });
    }
  });
  // 应用产品详情、修改等跳转
  table.on("tool(applyProductTable)", function (obj) {
    const data = obj.data;
    if (obj.event === "detail") {
      //详情
      window.location.href = "./serverProductDetial.html?productId=" + data.id;
    } else if (obj.event === "edit") {
      //修改
      window.dataProductId = data.id;
      layer.open({
        type: 2,
        title: "服务产品修改",
        area: ["1200px", "800px"],
        content: "./popupPage/serviceProductRegistratPop.html",
      });
    } else if (obj.event === "takeDown") {
      //下架
      $.ajax({
       timeout:30000,
        url: window.Http + "/dataProduct/operate",
        type: "POST",
        headers: {
          Authorization: "Bearer " + sessionStorage.getItem("Token"),
        },
        data: JSON.stringify({ id: data.id, status: -1 }),
        contentType: "application/json",
        success: function (res) {
          if (res.code === 200) {
            layer.msg("下架成功", { icon: 1 });
            algProductListReq();
          } else {
            layer.msg("下架异常", { icon: 2 });
          }
        },
      });
    } else if (obj.event === "shelves") {
      //上架
      $.ajax({
       timeout:30000,
        url: window.Http + "/dataProduct/operate",
        type: "POST",
        headers: {
          Authorization: "Bearer " + sessionStorage.getItem("Token"),
        },
        data: JSON.stringify({ id: data.id, status: 1 }),
        contentType: "application/json",
        success: function (res) {
          if (res.code === 200) {
            layer.msg("上架成功", { icon: 1 });
            algProductListReq();
          } else {
            layer.msg("上架异常", { icon: 2 });
          }
        },
      });
    }
  });
  // 混合套餐表格修改删除事件处理
  $("#mixPackageTable").delegate("a", "click", function (e) {
    // let dataId = $(this).parents("tr").attr("dataId");
    let productMixName = $(this).parents("tr").find(".productMixName").text();
    console.log(e.target.innerText);
    if (e.target.innerText === "修改") {
      window.mixProductName = productMixName;
      layer.open({
        type: 2,
        title: "服务产品修改",
        area: ["1200px", "800px"],
        content: "./popupPage/serviceProductRegistratPop.html",
      });
    } else if (e.target.innerText === "删除") {
      console.log(`e=${e}`);
      let productMixName = $(this).parents("tr").find(".productMixName").text();
      console.log(`productMixName=${productMixName}`);
      $.ajax({
       timeout:30000,
        url: window.Http + "/productMix/del",
        type: "DELETE",
        headers: {
          Authorization: "Bearer " + sessionStorage.getItem("Token"),
        },
        data: { productMixName },
        success: function (res) {
          if (res.code === 200) {
            layer.msg("删除成功", { icon: 1 });
            algProductListReq();
          } else {
            layer.msg(res.msg, { icon: 2 });
          }
        },
      });
    }
  });
  //刷新表格（用于弹窗调用）
  $("#reloadTable").click(function () {
    serviceProductTableRender(3);
    serviceProductTableRender(5);
    mixPackageProductFun();
  });
  /******************************************功能函数部分******************************************/
  /**
   * @Date：2023-09-23, 周六, 15:53
   * @description: 请求产品列表 并渲染表格
   * @param   {Object} params 请求参数 产品类型 5应用产品 3算法产品
   * @return {Promise} 请求的结果
   */
  function serviceProductListReq(params) {
    return new Promise(function (resolve, reject) {
      $.ajax({
       timeout:30000,
        url: window.Http + "/dataProduct/list",
        type: "GET",
        headers: {
          Authorization: "Bearer " + sessionStorage.getItem("Token"),
        },
        data: params,
        success: function (res) {
          if (res.code === 200) {
            resolve(res);
          } else {
            layer.msg(res.msg);
            reject(new Error("请求失败")); // 失败时将错误传递给调用者
          }
        },
      });
    });
  }
  /**
   * @description:函数描述 渲染表格和分页
   * @return 返回值 无
   * @param type {Number} 产品类型 5应用产品 3算法产品
   */
  function serviceProductTableRender(type) {
    serviceProductParams.sourceType = type;
    serviceProductListReq(serviceProductParams).then((res) => {
      if (type === 3) {
        algProductTable.reload({ data: res.rows });
      } else {
        applyProductTable.reload({ data: res.rows });
      }
      layui.laypage.render({
        elem: type === 3 ? "algProductTablePage" : "applyProductTablePage", //注意，这里的 test1 是 ID，不用加 # 号
        count: res.total, //数据总数，从服务端得到
        limit: 10,
        groups: 5,
        jump: function (obj, first) {
          if (!first) {
            console.log("obj.curr", obj.curr);
            serviceProductParams.currPage = obj.curr;
            serviceProductListReq(serviceProductParams).then((res) => {
              serviceProductListReq.reload({ data: res.rows });
            });
          }
        },
      });
    });
  }
  function mixPackageProductTableRender(data) {
    let html = "";
    let statushtml = `
						<td><a class="layui-btn layui-btn-xs layui-btn-normal text-white mr-2">修改</a>
						  <a class="layui-btn layui-btn-xs layui-btn-warm text-white mr-2">删除</a></td>`;
    data.forEach(function (val, index) {
      let applyProductNames = "",
        algProductNames = "";
      if (val.productSonList && val.productSonList.length > 0) {
        let data = val.productSonList;
        data.forEach(function (item, i) {
          if (item.sourceType == 3) {
            algProductNames += "," + item.productName;
          } else if (item.sourceType == 1 || item.sourceType == 3) {
            applyProductNames += "," + item.productName;
          }
        });
      }
      html +=
        `<tr dataId="` +
        val.id +
        `">
									<th scope="row">${index + 1}</th>
									<td class="productMixName">${val.productMixName}</td>
									<td>${applyProductNames}</td>
									<td>${algProductNames}</td>
									<td>${val.remark || ""}</td>
									` +
        statushtml +
        `
								</tr>`;
    });
    $("#mixPackageTable tbody").append(html);
  }
  //混合套餐产品列表渲染
  function mixPackageProductTableAndPageRender() {
    mixPackageProductReq(mixPackageProductParams).then((res) => {
      $("#mixPackageTable tbody").empty();
      if (res.rows && res.rows.length > 0) {
        mixPackageProductTableRender(res.rows);
        layui.laypage.render({
          elem: "mixPackageTablePage", //注意，这里的 test1 是 ID，不用加 # 号
          count: res.total, //数据总数，从服务端得到
          limit: 10,
          groups: 5,
          jump: function (obj, first) {
            if (!first) {
              console.log("obj.curr", obj.curr);
              mixPackageProductParams.currPage = obj.curr;
              mixPackageProductReq(mixPackageProductParams).then((res) => {
                mixPackageProductTableRender(res.rows);
              });
            }
          },
        });
      } else {
        let html = `<tr><td scope="row" colspan="8" style="text-align:center">暂无数据</td></tr>`;
        $("#mixPackageTable tbody").append(html);
      }
    });
  }
  //混合套餐产品列表
  function mixPackageProductReq(params) {
    return new Promise(function (resolve, reject) {
      $.ajax({
       timeout:30000,
        url: window.Http + "/productMix/list",
        type: "GET",
        headers: {
          Authorization: "Bearer " + sessionStorage.getItem("Token"),
        },
        data: params,
        success: function (res) {
          if (res.code === 200) {
            resolve(res);
          } else {
            layer.msg(res.msg);
            reject(new Error("请求失败")); // 失败时将错误传递给调用者
          }
        },
      });
    });
  }
  /**
   * @description:函数描述 获取产品总数和申购信息 在表格右上方展示
   * @return 返回值
   * @param Type {number} 3代表服务产品的
   */
  function requestStatistic(Type) {
    $.ajax({
       timeout:30000,
      url: window.Http + "/count/personal/data/table",
      type: "GET",
      headers: {
        Authorization: "Bearer " + sessionStorage.getItem("Token"),
      },
      data: { type: Type, ownUserId: sessionStorage.getItem("UserId") },
      success: function (res) {
        if (res.code === 200) {
          if (Type === 3) {
            $(".dataProductTotal").html(res.data.total || 0);
            $(".dataProductStatus").html(res.data.normal || 0);
            $(".buyCount").html(res.data.buyNum || 0);
          }
        }
      },
    });
  }
  requestStatistic(3);
  serviceProductTableRender(3);
});
